<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <table border="1" width="300" align="center">
      <thead>
        <tr>
          <th>编号</th>
          <th>姓名</th>
          <th>年龄<input type="button" id="sortAge" value="=" /></th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>

    <script>
      let up = '↑'
      let down = '↓'
      var data = [
        { name: 'rose', age: 19, id: '005' },
        { name: 'mark', age: 16, id: '003' },
        { name: 'jack', age: 18, id: '002' },
      ]

      //第二个要求
      function fillTable(source) {
        let tbody = document.querySelector('tbody')
        tbody.innerHTML = ''

        let result = ''
        for (let item of source) {
          let tr = `<tr><td>${item.id}</td><td>${item.name}</td><td>${item.age}</td></tr>`
          result += tr
        }
        tbody.innerHTML = result
      }
      fillTable(data)

      let sortbtn = document.querySelector('#sortAge')
      sortbtn.addEventListener('click', function () {
        if (this.value == '=') {
          this.value = down
        } else if (this.value == down) {
          this.value = up
          let sorteData = data.sort(function (m, n) {
            return m.age - n.age
          })
          fillTable(sorteData)
        } else {
          this.value = down
          let sorteData = data.sort(function (m, n) {
            return n.age - m.age
          })
          fillTable(sorteData)
        }
      })

      // let result = data.sort(function (a, b) {
      //   return a.age - b.age
      // })
      // console.log(result)

      // function sortFactory(name) {
      //   return function (m, n) {
      //     return m[name] - n[name]
      //   }
      // }

      // let result2 = data.sort(sortFactory('age'))
      // console.log(result2)

      // let result3 = data.sort(sortFactory('name'))
      // console.log(result3)

      // function sortFactory(infor) {
      //   return function (m, n) {
      //     let v1 = m[infor]
      //     let v2 = n[infor]

      //     if (v1 < v2) {
      //       return -1
      //     } else if (v1 > v2) {
      //       return 1
      //     } else {
      //       return 0
      //     }
      //   }
      // }
      // data = data.sort(sortFactory('age'))
      // console.log(JSON.stringify(data))
    </script>
  </body>
</html>
